package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.ws.rs.PUT;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理信息
 */
@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService{

    @Autowired
    private RoleDao roleDao;

    //添加角色管理
    @Override
    public void add(Role role,Integer[] permissionsIds){
        roleDao.add(role);
        //取出id 信息 遍历
        if(permissionsIds != null && permissionsIds.length > 0){
            //获取角色id值
            Integer roleId = role.getId();
            for (Integer permissionsId : permissionsIds) {
                Map<String,Integer> map = new HashMap<String,Integer>();
                map.put("roleId",roleId);
                map.put("permissionsId",permissionsId);
                //插入中间表数据
                roleDao.setPermissionIdAndRoleId(map);
            }
        }
    }
    //分页条件查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //取出数据
        Integer pageSize = queryPageBean.getPageSize();//每页显示条数
        Integer currentPage = queryPageBean.getCurrentPage();//当前页
        String queryString = queryPageBean.getQueryString();//根据条件查询
        //分页查询
        PageHelper.startPage(currentPage,pageSize);
        //根据条件查询
        Page<Role> page = roleDao.findByCondition(queryString);

        List<Role> rows = page.getResult();
        long total = page.getTotal();
        return new PageResult(total,rows);
    }

    /**
     * 根据id查询角色信息
     * @param id
     * @return
     */
    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    //编辑角色信息
    @Override
    public void edit(Role role,Integer[] permissionsIds){
        //修改角色信息
        roleDao.edit(role);
        //先删除中间关系表
        Integer roleId = role.getId();
        roleDao.deleteAssociation(roleId);

        //遍历permissions,重新插入中间关系表
        if(permissionsIds != null && permissionsIds.length > 0){
            for (Integer permissionsId : permissionsIds) {
                Map<String,Integer> map = new HashMap<String,Integer>();
                map.put("roleId",roleId);
                map.put("permissionsId",permissionsId);
                roleDao.setPermissionIdAndRoleId(map);
            }
        }

    }

    /**
     * 删除角色信息
     * @param id
     */
    @Override
    public void delete(Integer id) {
        //先删除对应的权限中间表
        roleDao.deleteAssociation(id);
        //删除角色表
        roleDao.deleteRole(id);

    }
}
